import http from './http'
import store from '@/store';
import Vue from 'vue'
//调试时修改这个域名控制H5,小程序需要更改appid
let baseUrl = 'https://www.lichu2025.cn/'
// https://www.lichu2025.cn/store/index

const intercept = (lock, img, is_show) => {
	http.config.baseUrl = baseUrl
	//设置请求前拦截器 */
	let passport = uni.getStorageSync('passport')
	http.interceptor.request = (config) => {
		config.header = {
			contentType: 'application/json',
			passport: passport
		}
	}

	//设置请求结束后拦截器
	http.interceptor.response = (e) => {
		// 请求错误处理
		if (e.statusCode !== 200) {
			let errorMessage = '网络错误,请稍后重试';
			if (e.statusCode === 404) {
				errorMessage = '请求的资源不存在';
			} else if (e.statusCode === 500) {
				errorMessage = '服务器内部错误';
			}
			uni.showToast({
				title: errorMessage,
				icon: "none",
				image: img,
				duration: 2000,
				mask: true,
			});
			return Promise.reject(new Error(errorMessage));
		}

		// 成功返回
		try {
			// 如果 e.data 是字符串，尝试解析为 JSON
			if (typeof e.data === 'string') {
				e.data = JSON.parse(e.data);
			}
			return e; // 返回解析后的数据
		} catch (error) {
			console.error('Failed to parse response data:', error);
			uni.showToast({
				title: '数据解析失败',
				icon: "none",
				image: img,
				duration: 2000,
				mask: true,
			});
			return Promise.reject(new Error('数据解析失败'));
		}
	};
}
// 检测登录
export const check_login = (theme) => {
	let userinfo = uni.getStorageSync('userinfo')
	let passport = uni.getStorageSync('passport')
	// if (userinfo.id == undefined || userinfo.id == 0 || passport == undefined || passport == '') {
	// 	uni.redirectTo({
	// 		url: '/pages/user/login'
	// 	})
	// }
}

export const log = (theme) => {
	//#ifdef APP-PLUS
	testModule && testModule.log(theme)
	//#endif
	console.log(theme)
}

export const toSelectBlue = () => {
	//#ifdef APP-PLUS
	testModule && testModule.gotoNativePage()
	//#endif
}

//公众号登录,is_check仅检测 get取openid
export const official_login = (appid, id) => {
	//#ifdef H5
	let ua = window.navigator.userAgent.toLowerCase()
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid +
			'&redirect_uri=' +
			baseUrl + 'pub/pay/gz_notify?id=' + id +
			'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true'
		return true
	}
	//#endif
	return false
}

export const toast = (msg) => {
	let img = '/static/err.png'
	uni.showToast({
		title: msg,
		icon: "none",
		image: img,
		duration: 1500,
		mask: true
	})
}

export const print = (data, fun) => {
	testModule.print(data, function(res) {
		if (res.status == 0) {
			print(data, fun)
		} else {
			fun()
			testModule.disconnect()
		}
	})
}

//跳转小程序
export const navigateToMiniProgram = (url) => {
	let ls = url.split("|")
	if (ls.length > 1) {
		uni.navigateToMiniProgram({
			appId: ls[0], //appid
			path: ls[1], //path
			success(res) {
				console.log('成功')
				// 打开成功
			},
			fail(res) {
				console.log('跳转小程序失败', res)
			},
		})
	}
}

export const get = (url, data, method = 'get', lock = 0, msg = '请求执行中.请稍后', is_show = false) => {
	let img = '/static/err.png'
	if (lock) {
		if (!getApp().globalData.ajs) {
			if (lock == 2) {
				uni.showToast({
					title: msg,
					icon: "success",
					image: img,
					duration: 1500,
					mask: true
				})
			}
			return (new Promise((resolve, reject) => {
				reject()
			}));
		} else {
			getApp().globalData.ajs = false
		}
	}

	if (is_show) {
		uni.showNavigationBarLoading()
		uni.showLoading({
			title: '数据载入中...',
			mask: true
		});
	}
	intercept(lock, img, is_show);
	return http.request({
		baseUrl: '',
		url: url,
		dataType: 'json',
		method: 'get',
		data: data,
	})
}
export const post = (url, data, method = 'post', lock = 0, msg = '请求执行中.请稍后', is_show = false) => {
	let img = '/static/err.png'
	if (lock) {
		if (!getApp().globalData.ajs) {
			if (lock == 2) {
				uni.showToast({
					title: msg,
					icon: "success",
					image: img,
					duration: 1500,
					mask: true
				})
			}
			return (new Promise((resolve, reject) => {
				reject()
			}));
		} else {
			getApp().globalData.ajs = false
		}
	}

	if (is_show) {
		uni.showNavigationBarLoading()
		uni.showLoading({
			title: '数据载入中...',
			mask: true
		});
	}
	intercept(lock, img, is_show);
	return http.request({
		baseUrl: '',
		url: url,
		dataType: 'json',
		method: method,
		data: data,
	})
}



// 单独导出(测试接口) import {test} from '@/common/vmeitime-http/'
export const hideget = (url, data, method = "GET", lock = 0, msg = '请求执行中.请稍后') => {
	// console.log(getApp().globalData.ajs)
	let img = '/static/err.png'
	if (lock) {
		if (!getApp().globalData.ajs) {
			if (lock == 2) {
				uni.showToast({
					title: msg,
					icon: "success",
					image: img,
					duration: 2000,
					mask: true
				})
			}
			return (new Promise((resolve, reject) => {}));
		} else {
			getApp().globalData.ajs = false
		}
	}

	intercept(lock, img);
	return http.request({
		baseUrl: '',
		url: url,
		dataType: 'json',
		method: method,
		data: data,
	})
}


export const upload_fun = (fun) => {
	uni.chooseImage({
		//一次性最多选择的图片张数，不写默认为9张。
		count: 1,
		sizeType: ['original', 'compressed'],
		sourceType: ['album', 'camera'],
		success: function(res) {
			//图片临时路径，可以作为img标签的src属性显示图片
			upload(res.tempFilePaths[0]).then(data => {
				getApp().globalData.ajs = true
				fun(data)
			})
		},
	})
}


//页面跳转
export const navigateTo = (event) => {
	if (event.indexOf('http') == 0) {
		//#ifdef H5
		window.location.href = event
		//#endif
		//#ifdef APP
		plus.runtime.openURL(event);
		//#endif
		//#ifdef MP
		uni.setStorageSync('online_customer', event)
		uni.navigateTo({
			url: '/pagesD/user/online_customer'
		})
		//#endif
	} else if (event.indexOf('|') > 0) {
		navigateToMiniProgram(event)
	} else {
		uni.navigateTo({
			url: event
		})
	}
}

export const upload = (imageSrc, lock = 2, msg = '文件上传中.请稍后') => {
	// console.log(getApp().globalData.ajs)
	let img = '/static/err.png'
	if (lock) {
		if (!getApp().globalData.ajs) {
			if (lock == 2) {
				uni.showToast({
					title: '上传失败',
					icon: "success",
					duration: 2000,
					mask: true
				})
			}
			return (new Promise((resolve, reject) => {}));
		} else {
			getApp().globalData.ajs = false
		}
	}
	uni.showNavigationBarLoading()
	uni.showLoading({
		title: '文件上传中...',
		mask: true
	});
	intercept(lock, img);
	return http.uploadFile({
		url: 'api/common/upload',
		filePath: imageSrc,
		fileType: 'image',
		name: 'file',
	})
}


// 默认全部导出  import api from '@/common/vmeitime-http/'
export default {
	get,
	post,
	toast,
	hideget,
	upload,
	check_login,
	official_login,
	upload_fun,
	navigateToMiniProgram,
	navigateTo,
	print,
	toSelectBlue,
	log,
	baseUrl
}